package io.itit.ecp.admin.server.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.itit.ecp.admin.common.enums.CarbonQuotaInputTypeEnums;
import io.itit.ecp.admin.server.entity.CarbonPriceDataEntity;
import io.itit.ecp.admin.server.entity.CarbonQuotaEntity;
import io.itit.ecp.admin.server.mapper.CarbonPriceDataMapper;
import io.itit.ecp.admin.server.mapper.CarbonQuotaMapper;
import io.itit.ecp.admin.server.service.ICarbonQuotaService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;


@Service
@RequiredArgsConstructor
public class CarbonQuotaServiceImpl extends JoinServiceImpl<CarbonQuotaMapper, CarbonQuotaEntity>
        implements ICarbonQuotaService {

    private final CarbonPriceDataMapper carbonPriceDataMapper;

    @Override
    public BigDecimal calculateCarbonIncome(String sceneProjectId, String inputType, BigDecimal quotaValue, Date date) {
        BigDecimal result = BigDecimal.ZERO;
        if (!StringUtils.pathEquals(inputType, CarbonQuotaInputTypeEnums.ADD.getValue())) {
            List<CarbonPriceDataEntity> list = carbonPriceDataMapper.selectList(new LambdaQueryWrapper<CarbonPriceDataEntity>()
                    .eq(CarbonPriceDataEntity::getSceneProjectId, sceneProjectId)
                    .ge(CarbonPriceDataEntity::getDataTime, DateUtil.beginOfDay(date))
                    .le(CarbonPriceDataEntity::getDataTime, DateUtil.endOfDay(date))
                    .orderByDesc(CarbonPriceDataEntity::getDataTime)
            );
            if (!list.isEmpty()) {
                result = list.get(0).getCarbonQuotaPrice().multiply(quotaValue);
                if (StringUtils.pathEquals(inputType, CarbonQuotaInputTypeEnums.PURCHASE.getValue())) { //购入为负数
                    result = result.negate();
                }
            }
        }
        return result;
    }
}
